/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package me.aviator.dao;

import java.io.File;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.BinaryType;
import static org.hibernate.type.StandardBasicTypes.BINARY;
import org.hibernate.type.TypeFactory;
import org.hibernate.usertype.EnhancedUserType;

public class PersistentByteArrayAsBlob implements EnhancedUserType, Serializable {

	private static final long serialVersionUID = -9178911693542286456L;

	public static final PersistentByteArrayAsBlob INSTANCE = new PersistentByteArrayAsBlob();

	private static final int[] SQL_TYPES = new int[] { Types.BLOB };

	public int[] sqlTypes() {
		return SQL_TYPES;
	}

	public Class<?> returnedClass() {
		return File.class;
	}

	public boolean equals(Object x, Object y) throws HibernateException {
		if (x == y) {
			return true;
		}
		if (x == null || y == null) {
			return false;
		}
		byte[] dtx = (byte[]) x;
		byte[] dty = (byte[]) y;
		return dtx.equals(dty);
	}

	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session,Object owner) throws HibernateException, SQLException {
		if (owner == null) {
			return null;
		}

		return rs.getBytes(names[0]);
	}

	public void nullSafeSet(PreparedStatement st, Object value, int index,SessionImplementor session) throws HibernateException, SQLException {
		if (value == null) {
			((BinaryType) (BINARY)).nullSafeSet(st, null, index,session);
			return;
		}

		byte[] bytes = (byte[]) value;

		((BinaryType) (BINARY)).nullSafeSet(st, bytes, index,session);
	}

	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	public boolean isMutable() {
		return false;
	}

	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}

	public String objectToSQLString(Object value) {
		throw new UnsupportedOperationException();
	}

	public String toXMLString(Object value) {
		return value.toString();
	}

	public Object fromXMLString(String xmlValue) {
		return new File(xmlValue);
	}

}
